package com.huan.drools.querys;

import lombok.extern.slf4j.Slf4j;
import org.drools.core.event.DebugProcessEventListener;
import org.kie.api.KieServices;
import org.kie.api.event.rule.DebugAgendaEventListener;
import org.kie.api.event.rule.DebugRuleRuntimeEventListener;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.QueryResults;
import org.kie.api.runtime.rule.Row;
import org.kie.api.runtime.rule.ViewChangedEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * drools 测试类
 */
@Slf4j
public class DroolsQueryApplication {

    public static void main(String[] args) {
        KieServices kieServices = KieServices.get();
        KieContainer kieContainer = kieServices.getKieClasspathContainer();
        KieSession kieSession = kieContainer.newKieSession("query-ksession");
        kieSession.addEventListener(new DebugRuleRuntimeEventListener());
        kieSession.addEventListener(new DebugAgendaEventListener());
        kieSession.addEventListener(new DebugProcessEventListener());

        Person person1 = new Person("张三", 16);
        Person person2 = new Person("李四", 17);
        Person person3 = new Person("王五", 30);

        kieSession.insert(person1);
        kieSession.insert(person2);
        kieSession.insert(person3);

        kieSession.fireAllRules();

        // 不带参数的query查询
        QueryResults queryResults = kieSession.getQueryResults("query01");
        queryResults.iterator().forEachRemaining(row -> {
            // 那么这个地方的 $p 是怎么来的呢？其实是我们自己编写的drl query中写的
            Person person = (Person) row.get("$p");
            log.info("query01从工作内存中获取的query: {}", person);
        });

        // 带参数的query查询
        queryResults = kieSession.getQueryResults("query02", 20);
        queryResults.iterator().forEachRemaining(row -> {
            Person person = (Person) row.get("$p");
            log.info("query02从工作内存中获取的query: {}", person);
        });

        kieSession.dispose();
    }
}
